package com.choudou5.solr.service;

import com.choudou5.solr.util.LogDeBugUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @name Service助手
 * @author choudou5
 * @date 2018-08-06
 */
public class ServiceHelper  {

    private static final Logger logger = LoggerFactory.getLogger(ServiceHelper.class);

    private static final Map<String, BaseService> cache = new HashMap<>();

    public static <S extends BaseService> S singleton(Class<S> clasz){
        String cacheKey = clasz.getName();
        S service = (S)cache.get(cacheKey);
        if(service == null){
            LogDeBugUtil.debug("实例化:"+cacheKey);
            service = getInstance(clasz);
            if(service != null){
                cache.put(cacheKey, service);
            }
        }
        return service;
    }

    private static <S extends BaseService> S getInstance(Class<S> clasz) {
        try {
            return (S)clasz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("实例化"+clasz, e);
        }
        return null;
    }
}
